package com.chuan.icons;

import java.io.BufferedReader;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;

import android.util.Log;

public class PyServer {
	protected final static String PYTHON_BIN = "/data/data/com.chuan.icons/python/bin/python";
	protected final static String PYTHONHOME = "/data/data/com.chuan.icons/python";
	protected final static String PYTHONPATH = "/sdcard/python";
	protected final static String SCRIPT_START_PATH = "/sdcard/icons_py/userver.py";
	protected final static String SHELL_BIN = "/system/bin/sh";

	protected static FileDescriptor mShellFd;
	public static FileOutputStream mShellOut;
	protected static FileInputStream mShellIn;
	protected static String mBuf;

	private static final String TAG = "afay";
	public static java.lang.Process mPythonProcess = null;
	protected static PrintStream mOut;
	protected static BufferedReader mIn;

	// Use this thread to check whether the subprocess is alive.
	public static Thread monitor_thread = null;

	public static void initServer() {
		if (monitor_thread != null) {
			if (monitor_thread.isAlive()) {
				return;
			}
		}

		if (!startBySDK(SCRIPT_START_PATH)) {
			Log.e(Constants.LOG_FLAG, "Start python process fail.");
			return;
		}
	}

	public static Boolean startBySDK(String script_path) {
		String[] envp = new String[2];
		envp[0] = "PYTHONHOME=" + PYTHONHOME;
		envp[1] = "PYTHONPATH=" + PYTHONPATH;

		try {
			mPythonProcess = Runtime.getRuntime().exec(
					PYTHON_BIN + " " + script_path, envp, null);

			mIn = new BufferedReader(new InputStreamReader(mPythonProcess
					.getInputStream()));
		} catch (IOException e1) {
			Log.e(Constants.LOG_FLAG, "Start python fail.", e1);
			return false;
		}

		monitor_thread = new Thread(new Runnable() {
			public void run() {
				try {
					doLog();
					mPythonProcess.waitFor();
				} catch (InterruptedException e) {
					Log.e(TAG, e.toString());
				}
				Log.e(TAG, "MONITOR THREAD DEAD.");
			}
		});

		monitor_thread.start();
		return true;
	}

	private static void doLog() {
		String line = "";
		while (true) {
			try {
				line = PyServer.mIn.readLine();
			} catch (IOException e) {
				break;
			}
			if (line == null) {
				break;
			}
			Log.d("afay", line);
		}
	}

	public static void stopServer() {
		if (monitor_thread == null) {
			return;
		}

		if (monitor_thread.isAlive()) {
			mPythonProcess.destroy();
		}

		while (monitor_thread.isAlive()) {
			try {
				monitor_thread.join();
			} catch (InterruptedException e) {
				Log.e(TAG, "Failed while stop server." + e.toString());
			}
		}
	}
}
